<template>
    <div class="card">
        <Toast />
        <Tabs value="0">
            <TabList style="display: flex; align-items: center; border-bottom: 1px solid #eee;">
                <!-- 左侧 Tab 列表 -->
                <div style="display: flex;">
                    <Tab v-for="(template, i) in templateList" :value="i" @click="onTemplateSelect(template)" :key="i">
                        {{ template.Label }}
                    </Tab>
                </div>

                <!-- 新增访谈按钮（视觉上像一个 Tab） -->
                <Button @click="openNewTemplate" style="  padding: 0px 10px;  border: 1px solid #d9d9d9;
                    border-radius: 4px ; color: white;   background-color: green;
                    cursor: pointer; margin-left: auto;">
                    新增访谈
                </Button>
            </TabList>
            <div class="flex flex-nowrap items-center mt-3 gap-2">

                <span class="text-red-500 pr-3">{{ currnteTemplate.Author }}</span>
                <span class="text-red-500 pr-3">{{ CommonService.formatFullDate(currnteTemplate.Creattime) }}</span>
                <InputText style="border-radius: 0.4rem; border: 1px solid burlywood;" class="flex-grow"
                    v-model="currnteTemplate.AnalysisPrompt"></InputText>
            </div>
        </Tabs>
        <div class="flex flex-col p-1">
            <ul v-for="(question, j) in QuestionList" :key="j" style="font-size: 1rem;">
                <li class="flex  mt-5">
                    <span class=" w-40">第{{ j + 1 }}问: </span>
                    <!-- 使用 v-model 实现双向绑定 -->
                    <InputText style="border-radius: 0.4rem; border: 1px solid burlywood; " class="   w-full"
                        v-model="QuestionList[j]"></InputText>
                    <Button class=" ml-2 " severity=" warn" @click="deleteQuestions(j)" icon=" pi pi-trash">
                    </Button>
                </li>
            </ul>
            <div class="flex flex-row gap-4 justify-between items-center m-10 ">
                <Button type="submit" label="新增问题" @click="addQuestions" severity="success"></Button>
                <Button type="submit" label="保存访谈" @click="saveQuestions(currnteTemplate.Id)" severity="warn"></Button>
            </div>
        </div>

    </div>
    <ModalInput label="输入新的访谈模板名称" @confirm="handleConfirm" ref="modalInputRef" />
</template>

<script setup lang="ts">
import { QuestionService } from '@/service/Question';
import { useToast } from 'primevue/usetoast';
import { onMounted, ref } from 'vue';
import ModalInput from '../../components/ModalInput.vue';
import Toast from 'primevue/toast';

import { CommonService } from "../common";

let _toast = null;
const getToast = () => {
    if (!_toast) {
        try {
            _toast = useToast();
        } catch (e) {
            console.warn('PrimeVue Toast 服务不可用:', e.message);
        }
    }
    return _toast;
};

// 错误处理函数
const handleError = (severity, Title) => {
    const toast = getToast();
    if (toast) {
        toast.add({ severity: severity, summary: 'Error Message', detail: Title, life: 3000 });
    } else {
        // 降级处理：使用console输出
        console[severity === 'error' ? 'error' : 'warn']('Toast不可用:', Title);
    }
};
let QuestionList = ref<string[]>([]);
let currnteTemplate = ref({
    Id: 0,
    Label: "",
    Desc: "",
    Author: "",
    AnalysisPrompt: "",
    AuthorSn: "",
    Creattime: "",
    Questions: []
});
let templateList = ref([]);
onMounted(() => {
    getAllTemplate();
})
function getAllTemplate() {
    templateList.value = [];
    QuestionService.getAllTemplate().then((result) => {
        if (result.Code != 1000) {
            handleError('error', result.Title);
            return
        } else {
            if (result.Data.length == 0) {
                handleError('error', "暂时没有访谈模板");
                return
            }
            result.Data.forEach((item) => {
                item.Questions = JSON.parse(item.Questions);
                templateList.value.push(item);
            })
            onTemplateSelect(templateList.value[0])
        }
    }).catch((error) => {
        handleError('error', '查询访谈模板出错');
    });
}
function onTemplateSelect(item) {
    QuestionList.value = item.Questions;
    currnteTemplate.value = item;
}


// 引用 ModalInput 组件
const modalInputRef = ref<InstanceType<typeof ModalInput>>();


// 打开模态框的方法
const openNewTemplate = () => {
    modalInputRef.value?.open();
};

// 确认事件处理函数
const handleConfirm = (value: string) => {
    QuestionService.addQuestionTemplate(value).then((result) => {
        if (result.Code != 1000) {
            handleError('error', result.Title);
            return
        } else {
            templateList.value.push(result.Data)
        }
    }).catch((error) => {
        handleError('error', '查询访谈模板出错');
    });
};


// 新增问题
function addQuestions() {
    QuestionList.value.push("");
}


// 删除问题
function deleteQuestions(index: number) {
    QuestionList.value.splice(index, 1);
}


// 保存问题
function saveQuestions(templateID: number) {
    const updatedTemplate = {
        ...currnteTemplate.value,
        Questions: JSON.stringify(QuestionList.value)
    };
    QuestionService.updateTemplate(templateID, updatedTemplate).then((result) => {
        if (result.Code != 1000) {
            handleError('error', result.Title);
        } else {
            // 刷新模板列表
            // getAllTemplate();
            handleError('success', result.Title);
        }
    }).catch((error) => {
        handleError('error', '保存访谈模板出错' + error);
    });
}


</script>
